package com.gientech.elasticsearch.controller;

import com.gientech.elasticsearch.entity.ResponseBean;
import com.gientech.elasticsearch.entity.User;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
public class UserInfoController {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 用户登录
     * @return ResponseBean
     */
    @PostMapping("/login")
    public ResponseBean login(@RequestBody User user) {

        ResponseBean responseBean = new ResponseBean();

        // 获取所有用户信息
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(queryBuilder);
        NativeSearchQuery build = builder.build();

        //indexName动态指定
        SearchHits<User> user_info = elasticsearchRestTemplate.search(build , User.class ,IndexCoordinates.of("test_user_info"));

        List<User> userInfoList = new ArrayList<>();

        List<SearchHit<User>> hits = user_info.getSearchHits();
        if (hits.isEmpty()) {
            responseBean.setCode("401");
            responseBean.setMsg("用户信息不存在，登录失败，请注册用户。");
        } else {
            for (SearchHit hit : hits) {
                User userInfo = (User)hit.getContent();
                userInfoList.add(userInfo);
            }
        }

        // 判断缓存是否存在
        if (!userInfoList.isEmpty()) {
            // 用户信息存在
            if (userInfoList != null && userInfoList.size() > 0) {
                for (int i = 0; i < userInfoList.size(); i++) {
                    User userInfo = (User)userInfoList.get(i);
                    // 用户名是否一致
                    if (user.getName().equals(userInfo.getName()) && user.getPassword().equals(userInfo.getPassword())) {
                        responseBean.setCode("200");
                        responseBean.setMsg("用户信息正确，登录成功。");
                        break;
                    } else {
                        responseBean.setCode("400");
                        responseBean.setMsg("用户信息不正，登录失败。");
                    }
                }
            }
        } else {
            responseBean.setCode("401");
            responseBean.setMsg("用户信息不存在，登录失败，请注册用户。");
        }
        // 返回结果
        return responseBean;
    }

    /**
     * 用户注册
     * @return ResponseBean
     */
    @PostMapping(value = {"/register"}, produces = {"application/json;charset=UTF-8"})
    @Transactional
    public ResponseBean regiestUser(@RequestBody User user) {

        // 用户信息注册
        //indexName默认取@Document中的indexName
        elasticsearchRestTemplate.save(user);

        //indexName动态制定--索引如果不存在save会自动创建后再存入数据
        elasticsearchRestTemplate.save(user, IndexCoordinates.of("test_user_info"));

        // 返回结果
        ResponseBean responseBean = new ResponseBean();
        responseBean.setCode("200");
        responseBean.setMsg("注册成功。");

        return responseBean;
    }

    /**
     * 获取所有用户注册信息
     * @return ResponseBean
     */
    @GetMapping("/getUserInfoList")
    public ResponseBean getUserInfoList() {
        // 获取所有用户信息
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(queryBuilder);
        NativeSearchQuery build = builder.build();

        //indexName动态指定
        SearchHits<User> user_info = elasticsearchRestTemplate.search(build , User.class ,IndexCoordinates.of("test_user_info"));

        List<User> userInfoList = new ArrayList<>();

        List<SearchHit<User>> hits = user_info.getSearchHits();
        if (hits.isEmpty()) {
            ResponseBean responseBean = new ResponseBean();
            responseBean.setCode("500");
            responseBean.setMsg("查询失败。");
        } else {
            for (SearchHit hit : hits) {
                User userInfo = (User)hit.getContent();
                userInfoList.add(userInfo);
            }
        }

        // 返回结果
        ResponseBean responseBean = new ResponseBean();
        responseBean.setCode("200");
        responseBean.setMsg("查询成功。");
        responseBean.setData(userInfoList);

        return responseBean;
    }

    @PostMapping(value = {"/delete"}, produces = {"application/json;charset=UTF-8"})
    public ResponseBean delete(@RequestBody User user) {

        //根据ID删除-indexName默认取@Document中indexName
        elasticsearchRestTemplate.delete(user.getId(), User.class);

        //根据ID删除-indexName动态指定
        elasticsearchRestTemplate.delete(user.getId(), IndexCoordinates.of("test_user_info"));

        // 返回结果
        ResponseBean responseBean = new ResponseBean();
        responseBean.setCode("200");
        responseBean.setMsg("删除成功。");

        return responseBean;
    }

}
